package com.iweb.dao;

import com.iweb.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author jay
 * @date 2021/8/9
 * @desc
 */
public class BaseDao {
    /**
     * 执行通用的数据操作语句
     *
     * @param sql
     * @param params
     * @return
     */
    protected int executeUpdate(String sql, Object... params) throws Exception {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            int result = 0;
            // 2.获取连接对象
            connection = DBHelper.getConnection();

            // 3.1 创建Statement对象
            statement = connection.prepareStatement(sql);
            // 设值参数值
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    statement.setObject(i + 1, params[i]);
                }
            }

            // 3.3执行sql语句
            result = statement.executeUpdate();

            return result;
        } finally {
            // 3.关闭连接
            // 先释放statement资源
            if (statement != null) {
                statement.close();
            }
            DBHelper.close(connection);
        }
    }




    /**
     * 执行通用查询
     * @param connection
     * @param preparedStatement
     * @param params
     * @return
     * @throws Exception
     */
    protected ResultSet executeQuery(Connection connection, PreparedStatement preparedStatement,
                                   Object... params) throws Exception {
        // 准备参数
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        // 执行
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
}
